<template>
  <div>
    <box t1="商品管理" t2="添加商品">
      <el-row>
        <el-alert title="消息提示的文案" type="info" show-icon center :closable="false"></el-alert>
      </el-row>
      <br>
      <!-- 这里的activeIndex接受一个数字 -->
      <el-steps :space="300" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <br>
      <el-form
        :model="addGoodsForm"
        :rules="addGoodsRules"
        ref="addGoodsRef"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <!-- 左侧tab栏切换 -->
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="leaveHandle"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="cateList"
                :props="props"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单的Item项 -->
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border=""></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              multiple
              :headers="headerObj"
              :on-success="uploadSucess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="addBtn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
          <el-tab-pane label="完成" name="5">完成</el-tab-pane>
        </el-tabs>
      </el-form>
    </box>
    <el-dialog title="图片预览" :visible.sync="previewDialogVisible" width="50%">
      <img :src="previewPath" alt="" style="width:100%">
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      activeIndex: "0",
      addGoodsForm: {
        goods_name: "水果",
        goods_price: 10,
        goods_number: 10,
        goods_weight: 10,
        goods_cat: [],
        pics: [],
        goods_introduce: "123"
      },
      addGoodsRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" }
        ]
      },
      cateList: [],
      props: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      manyTableData: [],
      onlyTableData: [],
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      // 设置图片上传请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      previewPath: "",
      previewDialogVisible: false
    };
  },
  methods: {
    async getCateList() {
      const res = await this.$http.get("categories");
      if (res.meta.status != 200) return this.$message.error("获取分类失败");
      this.cateList = res.data;
    },
    handleChange() {
      if (this.addGoodsForm.goods_cat.length != 3)
        return (this.addGoodsForm.goods_cat = []);
    },
    leaveHandle(activeName, oldActiveName) {
      if ((oldActiveName == 0) & (this.addGoodsForm.goods_cat.length != 3)) {
        this.$message.error("请选择商品类型");
        return false;
      }
    },
    // 获取商品参数
    async getGoodsParams() {
      const res = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.selPath }
      });

      if (this.activeIndex == 1) {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        });
        this.manyTableData = res.data;
      } else if (this.activeIndex == "2") {
        this.onlyTableData = res.data;
      }
    },
    tabClick() {
      this.getGoodsParams();

      return;
    },
    handlePreview(file) {
      this.previewPath = file.response.data.url;
      this.previewDialogVisible = true;
    },
    handleRemove(file) {
      // 得到图片在服务器存储的路径
      const picPath = file.response.data.tmp_path;
      // 根据路径，找出pics数组中对应的索引值
      const index = this.addGoodsForm.pics.findIndex(
        item => item.pic === "picPath"
      );
      // 根据索引删除对应的图片路径
      this.addGoodsForm.pics.splice(index, 1);
    },
    uploadSucess(response) {
      const picInfo = {
        pic: response.data.tmp_path
      };
      this.addGoodsForm.pics.push(picInfo);
      console.log(this.addGoodsForm);
    },
    addGoods() {
      this.$refs.addGoodsRef.validate(async valid => {
        if (!valid) return this.$message.error("请输入必要信息");
        // Goods_cat和级联选择器数据绑定，不能直接修改否则报错
        // 利用lodash对addGoodsForm进行深拷贝
        const formData = _.cloneDeep(this.addGoodsForm);
        formData.goods_cat = formData.goods_cat.join(",");
        // 处理参数数据
        formData.attrs = [];

        this.manyTableData.forEach(item => {
          formData.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" ")
          });
        });
        this.onlyTableData.forEach(item => {
          formData.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          });
        });
        console.log(formData);
        console.log(this.manyTableData);
        const res = await this.$http.post("goods", formData);
        console.log(res.meta);

        if (res.meta.status != 201) return this.$message.error(res.meta.msg);
        this.$router.push("/goods");
        this.$message.success("添加商品成功");
      });
    }
  },
  created() {
    this.getCateList();
  },
  computed: {
    cateId() {
      if (this.addGoodsForm.goods_cat.length === 3)
        return this.addGoodsForm.goods_cat[2];
    },
    selPath() {
      if (this.activeIndex == "1") return "many";
      if (this.activeIndex == "2") return "only";
    }
  }
};
</script>

<style lang="less" scoped>
.el-step__title {
  font-size: 12px;
}
.addBtn {
  margin-top: 15px;
}
</style>